package gowcage.testandroid.RecyclerView;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

/**
 * Created by Administrator on 2017/4/10.
 */

public class SimpleDecoration extends RecyclerView.ItemDecoration {
    /**
     * 复写onDraw方法，从而达到在每隔条目的被绘制之前（或之后），让他先帮我们画上去几根线吧
     *
     * @param c
     * @param parent
     * @param state
     */

    private final int DIR_UP = 0;
    private final int DIR_RIGHT = 1;
    private final int DIR_DOWN = 2;
    private final int DIR_LEFT = 3;

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        //先初始化一个Paint来简单指定一下Canvas的颜色
        Paint paint = new Paint();
        paint.setColor(parent.getContext().getResources().getColor(android.R.color.darker_gray));
        paint.setStrokeWidth(2f);

        //获得RecyclerView中总条目数量
        int childCount = parent.getChildCount();

        //遍历一下
        for (int i = 0; i < childCount; i++) {
            /*if (i == 0) {
                //如果是第一个条目，就不画边框
                continue;
            }*/
            //获得子View，也就是一个条目的View，准备画上边框
            View childView = parent.getChildAt(i);

            //获得子View的长宽，以及在屏幕上的位置，方便得到边框的具体坐标
            float x = childView.getX();
            float y = childView.getY();
            int width = childView.getWidth();
            int height = childView.getHeight();

            getSpanCount(parent);
            DrawBorder(c, paint, x, y, width, height, DIR_UP);
        }
        super.onDraw(c, parent, state);
    }

    private void DrawBorder(Canvas c, Paint paint, float x, float y, int w, int h, int dir) {
        //根据这些点坐标画条目的四周的线
        //上
        c.drawLine(x, y, x + w, y, paint);
        //右
        c.drawLine(x + w, y, x + w, y + h, paint);
        //下
//        c.drawLine(x, y + h, x + w, y + h, paint);
        //左
        c.drawLine(x, y, x, y + h, paint);
    }

    private int getSpanCount(RecyclerView parent) {
        // 列数
        int spanCount = -1;
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {

            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            spanCount = ((StaggeredGridLayoutManager) layoutManager)
                    .getSpanCount();
        }
        return spanCount;
    }


}
